#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <cassert>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/sendfile.h>
using namespace std;

int main(int argc, char* argv[])
{
    if(argc <= 3)
    {
        cout << "Usage: " << argv[0] << " ip_address port_number filename" << endl;
        return 1;
    }

    const char* ip = argv[1];
    int port = atoi(argv[2]);
    const char* file_name = argv[3];

    int fileFd = open(file_name, O_RDONLY);
    assert(fileFd >= 0);
    struct stat stat_buf;
    fstat(fileFd, &stat_buf);

    struct sockaddr_in address;
    memset(&address, 0, sizeof(address));
    address.sin_family = AF_INET;
    inet_pton(AF_INET, ip, &address.sin_addr);
    address.sin_port = htons(port);

    int listenFd = socket(AF_INET, SOCK_STREAM, 0);
    assert(listenFd >= 0);

    int ret = bind(listenFd, (struct sockaddr*)&address, sizeof(address));
    assert(ret != -1);

    ret = listen(listenFd, 5);
    assert(ret != -1);

    struct sockaddr_in client;
    socklen_t client_addrlength = sizeof(client);
    int connFd = accept(listenFd, (struct sockaddr*)&client, &client_addrlength);
    if(connFd < 0)
    {
        cout << "errno is: " << errno << endl;
    }
    else
    {
        sendfile(connFd,fileFd,null,stat_buf.st_size);
        close(connFd);
    }

    close(listenFd);
    close(fileFd);
    return 0;
}